<template>
  <VDialog
    @close="handleClose"
    @save="save"
    :loading="loading"
    width="640"
    destroy-on-close
  >
    <template #content>
      <div class="my-[32px]">
        <div class="mb-[16px]">
          <div class="mb-[16px] text-[red]">注意:{{ tips?.msg }}</div>
          <span class="mr-[32px]"
            >已选择正常:
            <span class="text-[red] mx-[4px]">{{ tips?.validLength || 0 }}</span
            >条数据</span
          >
          <span
            >异常:
            <span class="text-[red] mx-[4px]">{{
              tips?.invalidLength || 0
            }}</span
            >条数据</span
          >
        </div>
        <template v-if="formValues.type == 1">
          <el-form-item label="状态变更">
            <VSelects
              v-model="formValues.state"
              placeholder="请选择"
              :dataSourse="optionsData?.virtual_credit_card_state || []"
              clearable
              filterable
            />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="负责人">
            <VCascader
              v-model="formValues.attribution"
              :multiple="false"
              placeholder="请选择"
            />
          </el-form-item>
        </template>
      </div>
    </template>
  </VDialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import {
  stateVirtualCreditCard,
  attributionVirtualCreditCard,
} from "../../api.js";
const props = defineProps({
  data: { type: Object, default: () => {} },
  optionsData: { type: Object, default: () => {} },
});
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const { optionsData } = toRefs(props);
const loading = ref(false);
const formValues = ref({});
const tips = ref({});
watch(
  () => props.data,
  (val) => {
    if (val) {
      const { ids, type } = val;
      formValues.value.ids = ids;
      formValues.value.type = type;
      tips.value = val;
    }
  }
);
const save = async () => {
  const isStateType = formValues.value?.type === 1;

  if (isStateType && !formValues.value?.state) {
    return ElMessage.warning("变更状态不能为空!");
  }

  if (!isStateType && !formValues.value?.attribution) {
    return ElMessage.warning("负责人不能为空!");
  }
  if(!formValues.value?.ids?.length){
    return ElMessage.warning("暂无选中的正常数据,请重新选择!");
  }
  loading.value = true;
  try {
    const action = isStateType
      ? stateVirtualCreditCard
      : attributionVirtualCreditCard;
    const { code, message } = await action(formValues.value);
    if (code !== 200) return ElMessage.error(message);

    ElMessage.success("修改成功!");
    handleClose(true);
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};
const handleClose = (refresh) => {
  formValues.value = {};
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped></style>
